﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using H2.NET.Web.Workflow.Services;
using log4net;
using Newtonsoft.Json;
using Ultimus.OC;
using Ultimus.WFServer;
using UServLib;
using H2.NET.Business.Core;
using H2.NET.Data.Common;
using System.Text;
using System.Data.SqlClient;
using H2.NET.DBUtility;

namespace H2.NET.Web.Workflow.Workflow
{
    public partial class AssignRecipient : BasePage
    {
        /// <summary>
        /// 日志记录
        /// </summary>
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public List<Task> CurrentSteps = new List<Task>();

        protected void Page_Load(object sender, EventArgs e)
        {
            var action = AksRequest.GetQueryStringValue("action");
            if (string.IsNullOrEmpty(action)) //默认页面加载
            {
                var processName = AksRequest.GetString("process").Trim();
                var incidentNo = AksRequest.GetInt("incident", 0);

                hidProcess.Value = processName;
                hidIncident.Value = incidentNo.ToString();

                var taskList = new Tasklist();
                taskList.LoadFilteredTasks(new TasklistFilter
                {
                    strProcessNameFilter = processName,
                    nIncidentNo = incidentNo,
                    nFiltersMask = Filters.nFilter_Current
                });

                //找出当前流程的当前步骤
                for (var i = 0; i < taskList.GetTasksCount(); i++)
                {
                    CurrentSteps.Add(taskList.GetAt(i));
                }

                taskList.LoadFilteredTasks(new TasklistFilter
                {
                    strProcessNameFilter = processName,
                    nIncidentNo = incidentNo,
                    nFiltersMask = Filters.nFilter_Urgent
                });
                for (var i = 0; i < taskList.GetTasksCount(); i++)
                {
                    var tsk = taskList.GetAt(i);
                    if (CurrentSteps.All(t => t.strTaskId != tsk.strTaskId))
                    {
                        CurrentSteps.Add(tsk);
                    }
                }

                taskList.LoadFilteredTasks(new TasklistFilter
                {
                    strProcessNameFilter = processName,
                    nIncidentNo = incidentNo,
                    nFiltersMask = Filters.nFilter_Overdue
                });
                for (var i = 0; i < taskList.GetTasksCount(); i++)
                {
                    var tsk = taskList.GetAt(i);
                    if (CurrentSteps.All(t => t.strTaskId != tsk.strTaskId))
                    {
                        CurrentSteps.Add(tsk);
                    }
                }

                //加载实例信息
                var incident = new Incident();
                incident.LoadIncident(processName, incidentNo);

            }
            else if (action == "save") //form提交
            {
                var taskIds = Request.Form.GetValues("taskid");
                if (taskIds == null)
                {
                    ErrorMsg("操作失败");
                    return;
                }
                var processName = AksRequest.GetString("hidProcess").Trim();
                var incidentNo = AksRequest.GetInt("hidIncident", 0);

                var flag = false;
                var desc = string.Empty;
                try
                {
                    foreach (var taskId in taskIds)
                    {
                        var strAssignConferToUser = AksRequest.GetString("recipient_" + taskId);

                        #region 从OC中查找用户信息
                        User userAssignConferTo = null;
                        var ocAssignConferToUser = new OrgChart();
                        if (!ocAssignConferToUser.FindUser(strAssignConferToUser, "", 0, out userAssignConferTo))
                        {
                            ErrorMsg("找不到此用户" + strAssignConferToUser);
                            return;
                        }
                        #endregion

                        var task = new Task();
                        task.InitializeFromTaskId(taskId);
                        desc += task.strAssignedToUserFullName;
                        flag = task.AssignTask(userAssignConferTo.strUserName);

                        //追加任务指派记录
                        AssignConferTo(task.strProcessName, task.nIncidentNo.ToString(), task.strStepName, clsCmm.comm_username, clsCmm.comm_userfullname
                            , userAssignConferTo.strUserName, userAssignConferTo.strUserFullName, "AssignTo");

                        desc += " => " + userAssignConferTo.strUserFullName + " ";
                    }

                    var incidentManageLog = new t_log_IncidentManage
                    {
                        Process = processName,
                        Incident = incidentNo,
                        Status = flag,
                        Action = "指派执行人",
                        Description = desc,
                        Creator = UserAPI.UserFullName,
                        CreateOn = DateTime.Now
                    };
                    Storage.Save(incidentManageLog);

                }
                catch (Exception ex)
                {
                    // 记录错误日志
                    var errorLog = new t_log_IncidentManage
                    {
                        Process = processName,
                        Status = false,
                        Action = "指派执行人",
                        Description = "ERROR:" + ex.Message,
                        Creator = UserAPI.UserFullName,
                        Incident = incidentNo,
                        CreateOn = DateTime.Now
                    };
                    Storage.Save(errorLog);

                    Logger.Error(ex.Message);
                    ErrorMsg(ex.Message);
                }

                if (flag)
                {
                    SuccessMsg();
                }
                else
                {
                    ErrorMsg("操作失败");
                }
            }
            else if (action == "search_recipient")
            {
                var jobService = new JobService();
                var keyword = AksRequest.GetString("keyword");

                var result = jobService.FindByKey(keyword).Select(t =>
                    new
                    {
                        id = t.name.Trim(),
                        name = t.fullname.Trim() + "<br />" + t.name
                    });

                Response.ContentType = "text/json";
                Response.Write(JsonConvert.SerializeObject(result));

                Response.End();
                return;
            }
        }

        private void AssignConferTo(string strProcess, string strIncident, string strStep, string strUserName, string strUserFullName, string strAssignedToUserName, string strAssignedToUserFullName, string strAssignedClass)
        {
            try
            {
                clsCmm.clsDB.Storage("oleDB");
                var dt = clsCmm.clsDB.Query("select * from t_AssignedTo where Process='" + strProcess + "' and Incident=" + strIncident + " and Step='" + strStep + "' and Time is null");
                if (dt.Rows.Count >= 1)
                {
                    var i = clsCmm.clsDB.ExcuteSql("update t_AssignedTo set Time=getdate() where Process='" + strProcess + "' and Incident=" + strIncident + " and Step='" + strStep + "' and Time is null");
                }

                var strInsert = "insert into t_AssignedTo(ID,Process,Incident,Step,UserName,UserFullName,AssignedToUserName,AssignedToUserFullName,AssignedClass,StartTime) values('"
                      + System.DateTime.Now.ToString("yyyyMMddHHmmss") + dt.GetHashCode().ToString() + "'"
                      + ",'" + strProcess + "'"
                      + "," + strIncident
                      + ",'" + strStep + "'"
                      + ",'" + strUserName + "'"
                      + ",'" + strUserFullName + "'"
                      + ",'" + strAssignedToUserName + "'"
                      + ",'" + strAssignedToUserFullName + "'"
                      + ",'" + strAssignedClass + "'"
                      + ",getdate()"
                      + ")";

                clsCmm.clsDB.ExcuteSql(strInsert);
            }
            catch (Exception ex)
            {

            }
        }

    }
}